package myUser;

import java.io.IOException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import oamMyvisit.Visitor;
import oamMyvisit.VisitorDao;

/**
 * Servlet implementation class Checkit
 */
@WebServlet("/Checkit")
public class Checkit extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Checkit() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		request.setCharacterEncoding("UTF-8");
		User u=new User();
		u.setUserName(request.getParameter("username"));
		u.setPassword(request.getParameter("pwd"));	
		int id=0;
		try {
			UserDao dao=new UserDao();
			id=dao.getUserid(u);
			if(id==0){	//数据库中没有匹配的id，页面跳转到login.jsp
				response.sendRedirect("login.jsp");
				return;
			}
			
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//正确的
		//修改在线用户
		HttpSession session=request.getSession();
		Visitor v=(Visitor)session.getAttribute("USER");
		v.setUserId(id);	//引用。同时变。
		//修改历史访客
		try {
			VisitorDao dao=new VisitorDao();
			dao.updateVisitor(v);
		} catch (NamingException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.sendRedirect("main.jsp");
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
